<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//用户登陆
class Welcome extends ST_Controller {

	public function __construct() {
        parent::__construct();

        //判断session是否存在
        if(!empty($_SESSION['user'])){
            redirect(site_url('home'));
        }
    }


	public function index(){

        $this->load->model('settings_mdl');
        $this->settings_mdl->set_conf();

        $cap = $this->verify();
        $data = array(
            'cap' => $cap
        );
        $this->load->view('default/login',$data);
	}

	/**
	 * 用户登录
	 */
	public function login(){
		if(!$this->input->is_ajax_request()){
			show_404();
		}

		$post = $this->input->post(NULL);

		if($post['cap'] != $this->session->word){
            unset($_SESSION['word']);
			die('验证码错误！');
		}

		unset($_SESSION['word']);

		if(empty($post['username']) || empty($post['password'])){
			die('帐号或者密码不能为空');
		}

        //model
        $this->load->model('users_mdl');
        $this->load->model('logs_mdl');

        $this->db->where('phone',$post['username']);
        $this->db->or_where('email',$post['username']);
        $this->db->where('password',md5($post['password']));

        $res = $this->users_mdl->get_one();
        //echo $this->db->last_query();
        //判断状态
        if($res['status'] != 1){
            die('您没有登陆权限，请联系公司管理员');
        }

        //更新登陆记录
        $data = array(
            'user_id' => $res['id'],
            'login_time' => $_SERVER['REQUEST_TIME']
        );
        $this->logs_mdl->create($data);

        //加入session
        unset($res['password']);
        $this->session->set_userdata(array('user'=>$res));

        echo 1;
	}

	/**
     * 验证码刷新
     */
    public function reset_cap(){
        $cap = $this->verify();
        echo $cap['image'];
    }

	/**
	 * 验证码
	 */
	public function verify(){
		$this->load->helper('captcha');
        $vals = array(
            'word'      => '',
            'img_path'  => './captcha/',
            'img_url'   => base_url('/captcha/'),
            //'font_path' => './public/font/droidsansmono__.ttf',
            'font_path' => './public/font/Droid Sans Fallback.ttf',
            'img_width' => '277',
            'img_height'    => 60,
            'expiration'    => 1,
            'word_length'   => 6,
            'font_size' => 25,
            'img_id'    => 'Imageid',
            'pool'      => '0123456789',

            // White background and border, black text and red grid
            'colors'    => array(
                'background' => array(255, 255, 255),
                'border' => array(215, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
            )
        );
        $cap = create_captcha($vals);
        //转换为一次性数据
        $this->session->set_userdata('word', $cap['word']);
        return $cap;
	}



}
